const Service = require('../../../core/service/ApiService');

class AdminService extends Service {

    //登录
    async login(account, pwd, remember) {
        const dao = this.service.admin.admin.dao;
        const admin = await dao.findAdminByAccount(account);
        if (!admin)
            throw new this.error.BusinessError('该账号不存在');
        const encryptedPwd = this.helper.sha1(pwd);
        if (encryptedPwd !== admin.pwd)
            throw new this.error.BusinessError('密码错误');
        this.ctx.session.account = admin.account;
        this.ctx.session.town_id = admin.town_id;
        if (remember) {
            this.ctx.session.maxAge = 604800000;  //7天
        }
        return {
            town_name:admin.town_name
        };
    }

    //修改密码
    async updatePwd(old_pwd, new_pwd) {
        const dao = this.service.admin.admin.dao;
        const pwdFromDb = await dao.findAdminPwd(this.ctx.session.account);
        if (!pwdFromDb)
            throw new this.error.BusinessError('账户不存在');
        const oldAdminPwd = this.helper.sha1(old_pwd);
        if (oldAdminPwd !== pwdFromDb) {
            throw new this.error.BusinessError('密码错误');
        }
        const newPwd = this.helper.sha1(new_pwd);
        await dao.updatePwd(this.ctx.session.account, newPwd);
    }

    //退出登录
    async logout() {
        this.ctx.session = null;
    }

}

module.exports = AdminService;
